﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace TCPServer
{
    public class DESFactory
    {
        /// <span  name="key" class="mceItemParam"></span>Key，長度必須為ASCII 字元</param>   
        /// <span  name="iv" class="mceItemParam"></span>IV，長度必須為ASCII 字元</param>
        private static readonly byte[] DESInitializationVector = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };


        public static Byte[] EncryptDES(Byte[] sourceBytes, Byte[] key) {
            string srcString = System.Text.Encoding.UTF8.GetString(sourceBytes);
            Byte[] outputBytes = System.Text.Encoding.UTF8.GetBytes(Encrypt(srcString, key, DESInitializationVector));
            return outputBytes;
        }

        public static Byte[] DecryptDES(Byte[] sourceBytes, Byte[] key) {
            string srcString = System.Text.Encoding.UTF8.GetString(sourceBytes);
            Byte[] outputBytes = System.Text.Encoding.UTF8.GetBytes(Decrypt(srcString, key, DESInitializationVector));
            return outputBytes;
        }

        private static string Encrypt(string value, Byte[] DESKey, Byte[] DESInitializationVector) {
            using (var cryptoProvider = new DESCryptoServiceProvider())
            using (var memoryStream = new MemoryStream())
            using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(DESKey, DESInitializationVector), CryptoStreamMode.Write))
            using (var writer = new StreamWriter(cryptoStream))
            {
                writer.Write(value);
                writer.Flush();
                cryptoStream.FlushFinalBlock();
                writer.Flush();
                return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
            }
        }

        private static string Decrypt(string value, Byte[] DESKey, Byte[] DESInitializationVector) {
            using (var cryptoProvider = new DESCryptoServiceProvider())
            using (var memoryStream = new MemoryStream(Convert.FromBase64String(value)))
            using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(DESKey, DESInitializationVector), CryptoStreamMode.Read))
            using (var reader = new StreamReader(cryptoStream))
            {
                return reader.ReadToEnd();
            }
        }

    }
}
